
package com.scalar.chiptrack.operations.process.actions;

import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.operations.process.ProcessStep;
import com.scalar.chiptrack.operations.process.VendorLocation;
import com.scalar.chiptrack.operations.process.dao.FinishedGoodsDAO;
import com.scalar.chiptrack.operations.process.dao.ProcessTrackDAO;
import com.scalar.chiptrack.operations.process.dao.ProductDao;
import com.scalar.chiptrack.operations.process.dao.VendorLocationDAO;
import com.scalar.chiptrack.operations.process.forms.FinishedGoodsForm;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.users.User;



public class FinishedGoodsAction extends ChipTrackAction {

    public ActionForward execute (ActionMapping mapping,
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response)
                                  throws Exception {

		int approvedStatus= 1;
        String STEP_TYPE = "Finished Goods";
        HttpSession session = request.getSession(false);
		User user = (User)session.getAttribute (SessionKeys.USER_KEY);
		if (user == null)
		{
			return (mapping.findForward ("login"));
		}
        String action = request.getParameter("action");
		if ((action != null) && (action.equalsIgnoreCase("save"))) 
		{
            DBTransaction dbTransaction = null;
            boolean success = false;

            FinishedGoodsForm fgForm = (FinishedGoodsForm) form;
			HashMap errors = validateForm (fgForm);
            if ((errors != null) && (errors.isEmpty() == false)) 
            {
                request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
            }
            else 
            {
                int processStepId = -1;
				processStepId = fgForm.getProcessStepId();
				ArrayList locations = getVendorLocations(request);
				
				
				//added by ravikanth on 18 Sep 2003 to check for duplicate part numbers in Product Map Table
				String[] partNumbers = new String[fgForm.getDupProductName().length+1];
				partNumbers[0] = fgForm.getProductName();
				for(int i=0; i < fgForm.getDupProductName().length ; i++)
				{
					partNumbers[i+1] = fgForm.getDupProductName()[i];
				}
				// added by ravikanth on 18 Sep 2003 
				// check for duplicates in Product_Map_Table
				String dupNames = ProductDao.checkDupInProductMapTable(partNumbers,processStepId,STEP_TYPE);
				
				
				//new method called by Bhaskar on 17 nov 2003 to avoid
				//the duplication of marketing part numbers.
				String dupMktPartNumber = "";
				String tempProcStepId = ProductDao.getProcessStepId( dbTransaction, fgForm.getMktPartNumber() );
				if ( tempProcStepId == null ) tempProcStepId = "";
				tempProcStepId = tempProcStepId.trim();
				if ( processStepId == -1 )
				{
					if ( "".equalsIgnoreCase( tempProcStepId ) == false )
					{
						dupMktPartNumber = fgForm.getMktPartNumber();
						//errors.put("Same Marketing Part Number "+fgForm.getMktPartNumber()+" already Present"," Please enter another Marketing Part Number");
						//throw new ScalarException("Duplicate Marketing Part Number");
					}
				}
				else
				{
					if ((tempProcStepId != "")&&( tempProcStepId.equalsIgnoreCase(processStepId+"")==false ))
					{
						dupMktPartNumber = fgForm.getMktPartNumber();
						//errors.put("Same Marketing Part Number "+fgForm.getMktPartNumber()+" already Present"," Please enter another Marketing Part Number");
						//throw new ScalarException("Duplicate Marketing Part Number");
					}
				}
				
				
				if( ( dupNames.length() > 0 ) || ( dupMktPartNumber.length() > 0 ) )
				{
					 ArrayList vendorLocations = null;
					 if(dupNames.length() > 0 )
						 errors.put ("Part Numbers Already exists ", dupNames );
					 else
						 errors.put ("Marketing Part Number Already exists ", dupMktPartNumber );
					//  Added by hareesh on 27th Septemebr 2003
					// -- START --
					 vendorLocations = getAllVendorLocations( request );
					 if ( vendorLocations == null ){
						 if(processStepId!=-1)
						 {
							vendorLocations = VendorDAO.getFinishedGoodsLocations (processStepId);
						 }
						 else
						 {
							vendorLocations = VendorDAO.getFinishedGoodsLocations ();
						 }
					 }
					 // -- END --
					 request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
					 request.setAttribute( "finishedGoodsForm" , fgForm );
					 request.setAttribute( "vendorLocations" , vendorLocations );
					 return ( mapping.findForward("failure") );
				}
			// upto here

			    try 
			    {
                    // start transaction
                    dbTransaction = DBTransaction.getInstance();
                    dbTransaction.begin();

					if(processStepId==-1)
					{
						//system.out.println ("when creating for the first time");
						

						// added by hareesh on 8th September 2003
						// -- START --
						// Step 0
						// to check name "part number" whether it exists already for another product or not.
						boolean result = false;
						if ( ( fgForm.getProductName() !=null ) && ( fgForm.getOldProductName() !=null ) ) 
						{
							if( ! fgForm.getOldProductName().trim().equals( fgForm.getProductName().trim() ) )
							{
								 result = ProcessTrackDAO.checkPartNumberExistsInTestBinAndFGBraodAndKit ( fgForm.getProductName().trim());
							}
						}
						if (result == true )
						{
							errors.put( "Duplicate Part Number","Another Product is already present with this Part Number : "+ fgForm.getProductName().trim());
						}
						
						/*new method called by Bhaskar on 17 nov 2003 to avoid
						//the duplication of marketing part numbers.
						String tempProcStepId = ProductDao.getProcessStepId( dbTransaction, fgForm.getMktPartNumber() );
						if ( tempProcStepId == null ) tempProcStepId = "";
						tempProcStepId = tempProcStepId.trim();
						if ( "".equalsIgnoreCase( tempProcStepId ) == false )
						{
							errors.put("Same Marketing Part Number "+fgForm.getMktPartNumber()+" already Present"," Please enter another Marketing Part Number");
							//system.out.println ("just before throwing exception in the insert condition");
							throw new ScalarException("Duplicate Marketing Part Number");
						}*/
						
						if ((errors != null) && (errors.isEmpty() == false)) 
						{
							request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
						}
						else 
						{
							// -- END --
							// Step 1
							// insert a record into Process_Step table and get the process step id
							processStepId = ProcessStep.getProcessStepID (dbTransaction, STEP_TYPE, STEP_TYPE, fgForm.getComments());
							
							// Step 2
							// Store Product Table information
							ProductDao.saveProcessStepProduct (dbTransaction,
													   processStepId,
													   fgForm.getMftPartNumber(), //fgForm.getProductName(),
													   fgForm.getBaseProductId(),
													   fgForm.getMktPartNumber(),
													   fgForm.getComments(),
													   ((fgForm.getIsApproved())? "0" : "1") );

							// Step 3
							// insert a row in Inventory_Step table
							FinishedGoodsDAO.storeFinishedGoodsData (dbTransaction, processStepId, fgForm);

							// Step 4
							// Update nextStepID in the previousStepID row
							ProductDao.updateNextProcessStepId (dbTransaction, fgForm.getPreviousStepId(), processStepId);

							// Step 4.1
							// added by hareesh on 2nd September 2003
							// To Update Product in Mark and FG Track Table and Test Bin Stepup
							// when Product Name is changed in  Product Step
							// -- START --
							if ( ( fgForm.getProductName() !=null ) && ( fgForm.getOldProductName() !=null ) )
							{

								if( ! fgForm.getOldProductName().trim().equals( fgForm.getProductName().trim() ) )
								{
									// since up to this mark_FG_track_table does not contains the process_step_id  of Finished Goods
									ProcessTrackDAO.updateFinishedGoodsTrackProductName(dbTransaction,
																		   -1, // processtep_id
																		   fgForm.getTrackId(),
																		   fgForm.getProductName(),
																		   fgForm.getOldProductName() );
                                }
							}
							// -- END --
	
							// Step 5
							// Save vendor locations
							
							if ((locations != null) && (locations.size() > 0)) {
								VendorLocationDAO.saveVendorLocations (dbTransaction, processStepId, locations.iterator());
							}
						
							//Added by ravikanth on 18 Sep 2003 
							// Step 6		
							// Save Duplicate names into Product_Map_Table
							
							if( fgForm.getDupProductName() != null && fgForm.getDupProductName().length > 0)
							{
								ProductDao.saveProductMap( dbTransaction , processStepId , fgForm.getDupProductName() , locations);
							}

							// Added by hareesh on 7th October 2003
							ProcessTrackDAO.updateMarkAndFG (dbTransaction, processStepId, fgForm.getTrackId(), fgForm.getPreviousStepName(),
							fgForm.getProductName(), ProcessTrackDAO.FG, "Inprocess");
	
							success = true;  // added by hareesh on 8th September 2003
						}
					}
					else
					{
						//system.out.println ("when editing the existing one");
                        // added by hareesh on 8th September 2003
                    	// -- START --
                    	// Step 0
                    	// to check name "part number" whether it exists already for another product or not.
                     	boolean result = false;
                     	if ( ( fgForm.getProductName() !=null ) && ( fgForm.getOldProductName() !=null ) ) 
                     	{
                            if( ! fgForm.getOldProductName().trim().equals( fgForm.getProductName().trim() ) )
                            {
                                 result = ProcessTrackDAO.checkPartNumberExistsInTestBinAndFGBraodAndKit ( fgForm.getProductName().trim());
                            }
	                     }

    	                 if (result == true )
    	                 {
							errors.put( "Duplicate Part Number","Another Product has already present with this Part Number : "+ fgForm.getProductName().trim());
                     	 }
						 
						 
						/*String processStepId1 = ProductDao.getProcessStepId( dbTransaction, fgForm.getMktPartNumber() );
						if ( processStepId1 == null )
						{
							processStepId1 = "";
							//system.out.println ("if the id is null");
						}
						//system.out.println ( "processStepId1 : "+processStepId1 );
						if ((processStepId1 != "")&&( processStepId1.equalsIgnoreCase(processStepId+"")==false ))
						{
							//system.out.println ("just before throwing exception in the update condition");
							throw new ScalarException("Duplicate Marketing Part Number");
						}*/
						 
                     	 if ((errors != null) && (errors.isEmpty() == false)) 
                     	 {
							 request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
                    	 }
                    	 else 
                    	 {
                    		// -- END --
							//Step 1:Update Process Step Table
							ProcessStep.updateProcessStepID(dbTransaction,STEP_TYPE,STEP_TYPE, fgForm.getComments(),processStepId);
							//system.out.println ("Step 1:Update Process Step Table");

							//Step 2:Update Product table
                            // changed by hareesh on 16th july 2003
							// to update maketing number in the product table also.

							// Modified by vasanth 08/18/2003 added the @param # 4
							// Inorder to save the status of a product (approved/not approved)
                            // -- START --
							
							/*ProductDao.updateProcessStepProduct( dbTransaction,
												 processStepId,
												 fgForm.getProductName(),
												 fgForm.getComments(),
												 fgForm.getBaseProductId() );*/
							
                            ProductDao.updateProcessStepProduct( dbTransaction,
                                                                 processStepId,
                                                                 fgForm.getProductName(),
                                                                 fgForm.getComments(),
																 fgForm.getIsApproved(),
                                                                 fgForm.getBaseProductId(),
                                                                 fgForm.getMktPartNumber());
							//system.out.println ("Step 1:ProductDao.updateProcessStepProduct(");
                            // -- END
							//Step 3:Update Inventory_Step table
							FinishedGoodsDAO.updateFinishedGoodsData (dbTransaction, processStepId, fgForm);
							//system.out.println ("Step 1:FinishedGoodsDAO.updateFinishedGoodsData");

                            // Step 3.1
                            // added by hareesh on 2nd September 2003
                            // To Update Product in Mark and FG Track Table and Test Bin Stepup
                            // when Product Name is changed in  Product Step
                            // -- START --
                            if ( ( fgForm.getProductName() !=null ) && ( fgForm.getOldProductName() !=null ) ) 
                            {
                            	if( ! fgForm.getOldProductName().trim().equals( fgForm.getProductName().trim() ) )
                            	{
                                	ProcessTrackDAO.updateFinishedGoodsTrackProductName(dbTransaction,
                                                                       processStepId,
                                                                       fgForm.getTrackId(),
                                                                       fgForm.getProductName(),
                                                                       fgForm.getOldProductName() );
									//system.out.println ("processTrackDAO.updateFinishedGoodsTrackProductName");
                                }
                          	}
                         	// -- END --

							//Step 4:Delete and Save new Vendor Locations
							VendorLocationDAO.deleteVendorLocations(dbTransaction,processStepId);
							if ((locations != null) && (locations.size() > 0)) 
							{
								VendorLocationDAO.saveVendorLocations (dbTransaction, processStepId, locations.iterator());
							}
							//Added by ravikanth on 18 Sep 2003 
							// Step 5		
							// Save Duplicate names into Product_Map_Table
							if( fgForm.getDupProductName() != null && fgForm.getDupProductName().length > 0)
							{
								ProductDao.saveProductMap( dbTransaction , processStepId , fgForm.getDupProductName() , locations);
							}
	                        success = true; // added by hareesh on 8th September 2003
                        }

                    }
    	               // End transaction
        	          // success = true; removed by hareesh on 8th september 2003
                }
                catch (ScalarException se) {
					
					if (se.getMessage().equals("Duplicate Marketing Part Number"))
					{
						errors.put("Same Marketing Part Number "+fgForm.getMktPartNumber()+" already Present"," Please enter another Marketing Part Number");
					}
                    // exception while storing Finished Goods information into databse
                    // log it
                    //se.getRootCause().printStackTrace();
                }
                finally {
                    // Rollback or Commit the Transaction

                    if (success == true) {
                        dbTransaction.commit();
                    }
                    else {
                        dbTransaction.rollback();
                    }
                }
				 if ((errors != null) && (errors.isEmpty() == false)) 
				 {
					 request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
				 }
                request.setAttribute ("processStepId", processStepId+"");                 //
                request.setAttribute ("previousStepId", fgForm.getPreviousStepId()+"");   // to be used in transport_locations page
                request.setAttribute ("trackId", fgForm.getTrackId()+"");                  //
                request.setAttribute ("productName", fgForm.getProductName());            // To be used in transport_locations page
                request.setAttribute ("previousStepName", fgForm.getPreviousStepName()); //
                request.setAttribute ("stepName", fgForm.getStepName());                   //
                request.setAttribute ("baseProductId", fgForm.getBaseProductId()+"");      //
                request.setAttribute ("comingFrom", "FINISHED_GOODS");                     //
            }

            if (success == true) {
                return (mapping.findForward ("success"));
            }

            // changed by hareesh on 27th Septemrber 2003
            // -- START --
            //ArrayList vendorLocations = VendorDAO.getFinishedGoodsLocations();
            //request.setAttribute ("vendorLocations", vendorLocations);
            ArrayList vendorLocations = getAllVendorLocations( request );
            if(vendorLocations == null){
                int processStepId = -1;
				processStepId = fgForm.getProcessStepId();
                if(processStepId!=-1)
                 {
                    vendorLocations = VendorDAO.getFinishedGoodsLocations (processStepId);
                 }
                 else
                 {
                    vendorLocations = VendorDAO.getFinishedGoodsLocations ();
                 }
            }
            request.setAttribute("vendorLocations", getAllVendorLocations(request));
            // -- END --
            return (mapping.findForward ("failure"));
        }

        int processStepId = Integer.parseInt (request.getParameter ("processStepID"));
        int trackId = Integer.parseInt (request.getParameter ("trackID"));

        FinishedGoodsForm fgForm = null;
        ArrayList vendorLocations = null;

        // added by hareesh on 7th October 2003
        String previousStepName = request.getParameter ("previousStepName");

        if (processStepId == -1) {  // New

            String stepName = request.getParameter ("stepName");
            //String previousStepName = request.getParameter ("previousStepName"); // changed by hareesh on 7th October 2003
            String productName = request.getParameter ("productName");
            int baseProductId = Integer.parseInt (request.getParameter ("baseProductID"));
            int previousStepId = Integer.parseInt (request.getParameter ("previousStepID"));

            fgForm = new FinishedGoodsForm();
            fgForm.setProductName (productName);
            fgForm.setBaseProductId (baseProductId);
            fgForm.setPreviousStepId (previousStepId);
            fgForm.setStepName (stepName);
            fgForm.setTrackId (trackId);
            fgForm.setPreviousStepName (previousStepName);

            // Added by hareesh on 2nd September 2003
             fgForm.setOldProductName(productName);

            vendorLocations = VendorDAO.getFinishedGoodsLocations();
        }
        else {  // Existing


            fgForm = FinishedGoodsDAO.loadFinishedGoodsData (processStepId);
			// begin--added by vasanth 08/17/2003 to populate the checkbox isApproved
			fgForm.setIsApproved(FinishedGoodsDAO.isApprovedFinishedGoods(processStepId));
			// end--
			fgForm.setTrackId (trackId);
            fgForm.setProcessStepId (processStepId);

            fgForm.setPreviousStepName (previousStepName); // added by hareesh on 7th October 2003

            vendorLocations = VendorDAO.getFinishedGoodsLocations (processStepId);

        }

		//request.setAttribute("approvedStatus", approvedStatus+"");
        request.setAttribute ("vendorLocations", vendorLocations);
        request.setAttribute ("finishedGoodsForm", fgForm);

        return (mapping.findForward("show"));
    }

     private HashMap validateForm (FinishedGoodsForm fgForm) {

        HashMap errors = new HashMap();

        try {
            Integer.parseInt (fgForm.getMaxLevel());
        }
        catch (NumberFormatException nfe) {
            errors.put ("Max Level", "Invalid number entered for Max Level");
        }

        try {
            Integer.parseInt (fgForm.getMinLevel());
        }
        catch (NumberFormatException nfe) {
            errors.put ("Min Level", "Invalid number entered for Min Level");
        }

        try {
            Integer.parseInt (fgForm.getReorderLevel());
        }
        catch (NumberFormatException nfe) {
            errors.put ("Re-Order Level", "Invalid number entered for Re-Order Level");
        }

        return errors;
    }

     private ArrayList getVendorLocations (HttpServletRequest request) {

        ArrayList vendorLocations = new ArrayList();

        String[] locationName = request.getParameterValues("locationName");
        if (locationName == null) {
            return null;
        }

	String[] priority = request.getParameterValues("priority");
	String[] locationID = request.getParameterValues("locationID");;

        VendorLocation location = null;
        String select = null;

        for (int i=0; i<locationName.length; i++) {

            select = request.getParameter("select_"+i);
            if (select != null) {    // check if this row was enabled by the user or not
                                     // save only if its enabled

                location = new VendorLocation (select,
                                          // priority[i],
                                          // changed by hareesh on 25th August 2003 // not get -1's if value not entered
                                           ( priority[i] !=null && priority[i].trim().length() != 0 ? priority[i] : "0" ),
                                            locationName[i],
                                            locationID[i]);
                vendorLocations.add (location);
            }
        }

        return vendorLocations;
    }

    // added by hareesh on 8th Septemeber 2003
    // -- START --
    private ArrayList getAllVendorLocations (HttpServletRequest request) {

        ArrayList vendorLocations = new ArrayList();
        String[] locationName = request.getParameterValues("locationName");
        if (locationName == null) {
            return null;
        }
    	String[] priority = request.getParameterValues("priority");
	    String[] locationID = request.getParameterValues("locationID");;
        VendorLocation location = null;
        String select = null;
        for (int i=0; i<locationName.length; i++) {
            select = request.getParameter("select_"+i);
            if (select != null) {    // check if this row was enabled by the user or not
                 select = "on";                    // save only if its enabled
            }else {
              select = "";
            }
           location = new VendorLocation (select,
                                          // priority[i],
                                          // changed by hareesh on 25th August 2003 // not get -1's if value not entered
                                           ( priority[i] !=null && priority[i].trim().length() != 0 ? priority[i] : "" ),
                                            locationName[i],
                                            locationID[i]);
            vendorLocations.add (location);

        }

        return vendorLocations;
    }

    // -- END --


}